<template>
  <div class="search-result-page">
    <div class="page-header">
      <h1 class="page-title">搜索结果</h1>
      <p class="search-info" v-if="keyword">关键词：<span class="keyword">{{ keyword }}</span>，找到 {{ total }} 条结果</p>
    </div>
    
    <div class="search-filter">
      <a-space>
        <a-radio-group v-model:value="sortBy" button-style="solid">
          <a-radio-button value="relevance">相关度</a-radio-button>
          <a-radio-button value="latest">最新发布</a-radio-button>
        </a-radio-group>
      </a-space>
    </div>
    
    <div class="search-result-container">
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
      </div>
      
      <template v-else>
        <div v-if="searchResults.length > 0" class="result-list">
          <div v-for="item in searchResults" :key="item.id" class="result-item" @click="goToDetail(item.id)">
            <div class="result-image" v-if="item.imageUrl">
              <img :src="item.imageUrl" :alt="item.title" />
            </div>
            <div class="result-content">
              <h3 class="result-title">{{ item.title }}</h3>
              <p class="result-summary">{{ item.summary }}</p>
              <div class="result-meta">
                <span class="result-category">{{ getCategoryName(item.category) }}</span>
                <span class="result-author">{{ item.author }}</span>
                <span class="result-date">{{ formatDate(item.publishTime) }}</span>
                <span class="result-views"><eye-outlined /> {{ item.viewCount }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <a-empty v-else description="未找到相关新闻，请尝试其他关键词" />
      </template>
      
      <div class="pagination-container" v-if="total > 0">
        <a-pagination
          v-model:current="currentPage"
          :total="total"
          :page-size="pageSize"
          show-quick-jumper
          @change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { EyeOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 状态变量
const loading = ref(false)
const searchResults = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const sortBy = ref('relevance')

// 从URL获取搜索关键词
const keyword = computed(() => route.query.keyword || '')

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取分类名称
const getCategoryName = (category) => {
  const categoryMap = {
    'important': '学校要闻',
    'academic': '学术动态',
    'general': '综合新闻',
    'notice': '通知公告'
  }
  return categoryMap[category] || '新闻'
}

// 搜索新闻
const searchNews = async () => {
  if (!keyword.value.trim()) {
    searchResults.value = []
    total.value = 0
    return
  }
  
  loading.value = true
  try {
    // 实际项目中应该调用API
    // const response = await axios.get('/api/news/search', {
    //   params: {
    //     keyword: keyword.value,
    //     page: currentPage.value,
    //     pageSize: pageSize.value,
    //     sortBy: sortBy.value
    //   }
    // })
    // const data = response.data
    // searchResults.value = data.items
    // total.value = data.total
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 600))
    
    // 生成模拟搜索结果
    const mockResults = []
    const resultCount = Math.floor(Math.random() * 30) + 5
    const categories = ['important', 'academic', 'general', 'notice']
    
    for (let i = 1; i <= resultCount; i++) {
      const category = categories[Math.floor(Math.random() * categories.length)]
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 30))
      
      mockResults.push({
        id: i + 1000,
        title: `包含"${keyword.value}"的${getCategoryName(category)}新闻标题 ${i}`,
        summary: `这是一条包含"${keyword.value}"关键词的新闻摘要，属于${getCategoryName(category)}类别。这里是更多的描述内容...`,
        category,
        imageUrl: Math.random() > 0.3 ? `https://via.placeholder.com/120x80?text=${encodeURIComponent(getCategoryName(category))}` : null,
        author: '新闻中心',
        publishTime: date.toISOString().split('T')[0],
        viewCount: Math.floor(Math.random() * 1000) + 100
      })
    }
    
    // 排序
    if (sortBy.value === 'latest') {
      mockResults.sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime))
    }
    
    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    searchResults.value = mockResults.slice(start, end)
    total.value = mockResults.length
    
  } catch (error) {
    message.error('搜索失败，请稍后再试')
    console.error('搜索失败:', error)
    searchResults.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  searchNews()
  // 滚动到顶部
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

// 跳转到新闻详情
const goToDetail = (id) => {
  router.push(`/news/${id}`)
}

// 监听关键词和排序变化
watch(() => keyword.value, () => {
  currentPage.value = 1
  searchNews()
})

watch(() => sortBy.value, () => {
  searchNews()
})

// 组件挂载时执行搜索
onMounted(() => {
  searchNews()
})
</script>

<style scoped>
.search-result-page {
  padding-bottom: 30px;
}

.page-header {
  margin-bottom: 20px;
}

.search-info {
  margin-top: 10px;
  color: #666;
}

.keyword {
  color: #003366;
  font-weight: bold;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.search-result-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.result-item {
  display: flex;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.result-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.result-image {
  flex: 0 0 120px;
  margin-right: 15px;
}

.result-image img {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.result-content {
  flex: 1;
}

.result-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 10px;
  color: #003366;
}

.result-summary {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.result-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.result-category {
  color: #003366;
  font-weight: bold;
}

.result-views {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .result-item {
    flex-direction: column;
  }
  
  .result-image {
    flex: none;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .result-image img {
    width: 100%;
    height: auto;
    max-height: 150px;
  }
  
  .result-title {
    font-size: 16px;
  }
}
</style>